<script setup>
import Edit from './components/Edit.vue'
import axios from 'axios'
import {ElMessageBox, ElMessage} from  'element-plus'
import { onMounted,ref ,getCurrentInstance } from 'vue';
computed()

const instance = getCurrentInstance()
const { proxy } = getCurrentInstance();
const list=ref(null)
// TODO: 列表渲染
onMounted(()=>{
 getList()
})
const getList=async ()=>{
  let {data}=await axios('/list')
  list.value=data
}
// TODO: 删除功能
const del=async(id)=>{
  ElMessageBox.confirm(
    '确定要删除吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await axios.delete(`/del/${id}`)
      getList()
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除失败',
      })
    })

}

const editDialog=ref(null)
const dialogList=ref([])
const ids=ref()
const typeA=ref()
const edit=(type,row)=>{
  typeA.value=type
  editDialog.value.open()
  dialogList.value=row
  ids.value=row.id
}

//编辑
const submitA=async()=>{
  await axios.patch(`/edit/${ids.value}`, {
    name: dialogList.value.name,
    place:  dialogList.value.place,
})
instance.proxy.$message.success('编辑成功')
editDialog.value.close()
getList()

}

//添加
const add=(type)=>{
  typeA.value=type
  editDialog.value.open()
}
</script>

<template>
  <div class="app">
    <el-button type="primary" link @click="add">添加</el-button>
    <el-table :data="list">
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="姓名" prop="name" width="150"></el-table-column>
      <el-table-column label="籍贯" prop="place"></el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{row}">
          <el-button type="primary" link @click="edit(row)">编辑</el-button>
          <el-button type="danger" link @click="del(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <Edit  ref="editDialog"  :dialogList="dialogList" @submitA="submitA"/>
</template>

<style scoped>
.app {
  width: 980px;
  margin: 100px auto 0;
}
</style>
